package com.usiful.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * shell 工具
 * @author [周织能]
 *
 */
public class ShellUtil {

	public final static int SHELL_EXEC_SUCC = 0;
	public final static int SHELL_EXEC_FAIL = -1;
	
	public static class ShellCmdResult{
		public String desc;		//描述字符
		public int  errcode;		//错误码 0 succ -1 error
	}
	
	public static ShellCmdResult exec(String cmd,String[] args) throws Exception {
		ShellCmdResult result = new ShellCmdResult();
		Runtime run = Runtime.getRuntime();
		for(String arg : args) {
			cmd += " " + arg;
		}
		System.out.println("the exec cmd======>" + cmd);
		Process p = run.exec(cmd);// 启动另一个进程来执行命令  
	     StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");           
         errorGobbler.start();  
         StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), "STDOUT");  
         outGobbler.start();
        //检查命令是否执行失败。  
        if (p.waitFor() != 0) {  
        	//阻塞到命令返回
            if (p.exitValue() == 1){//p.exitValue()==0表示正常结束，1：非正常结束  
                result.desc = "命令执行失败!";
                result.errcode = SHELL_EXEC_FAIL;
            } else {
            	result.desc = "命令执行成功!";
                result.errcode = SHELL_EXEC_SUCC;
            }
            
        }   
		return result;
	}
	
	public static class StreamGobbler extends Thread {  
	    InputStream is;  
	    String type;  
	    OutputStream os;  

	    StreamGobbler(InputStream is, String type) {  
	        this(is, type, null);  
	    }  

	    StreamGobbler(InputStream is, String type, OutputStream redirect) {  
	        this.is = is;  
	        this.type = type;  
	        this.os = redirect;  
	    }  

	    public void run() {  
	        InputStreamReader isr = null;  
	        BufferedReader br = null;  
	        PrintWriter pw = null;  
	        try {  
	            if (os != null)  
	                pw = new PrintWriter(os);  

	            isr = new InputStreamReader(is);  
	            br = new BufferedReader(isr);  
	            String line=null;  
	            while ( (line = br.readLine()) != null) {  
	                if (pw != null)  
	                    pw.println(line);  
	                System.out.println(type + ">" + line);      
	            }  

	            if (pw != null)  
	                pw.flush();  
	        } catch (IOException ioe) {  
	            ioe.printStackTrace();    
	        } finally{  
	            try {  
	            	if(pw != null)
	            		pw.close();  
	                br.close();  
	                isr.close();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	        }  
	    }  
	}   
}
